/* eslint-disable prettier/prettier */
import { GlobalData } from '/store/state'
import { getDomoUser, getUser } from '/store/actions'
import { $event } from '/utils'
import { mallApi } from '/api/mall'
import { checkUserisVip } from '/store/mutations'
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'

Page({
  data: {
    commodityId: '',
    orig: true,
    top: GlobalData.menuRect.top,
    height: GlobalData.menuRect.height,
    currencyName: GlobalData.currencyName,
    // 收货地址
    realname: '',
    phone: '',
    province: '',
    city: '',
    country: '',
    detail: '',
    info: {} as DomoCommodity,
    count: 1,
    options: '',
    countPrice: 0,
    countPrices: 0,
    score: 0,
    exchangeRate: 0.1,
    /** 管理/完成 */
    operation: false,
    /** 商品总数量 */
    totalCount: 0,
    list: [] as any[],
    /** 购物车数据是否已经加载完毕了 */
    listLoadAll: false,
    /** 是否全选 */
    selectedAll: false,
    /** 选中的列表 */
    chooseList: [] as any[],
    price: 0,
    /** 结算商品列表 */
    priceList: [] as any[],
    loaded: true,
    user: {} as DomoUser,
    /** 总运费 */
    freight: 0,
    /** 推荐商品数据 */
    pushList: [],
    /** 推荐数据是否是最后一页了 */
    isLastpage: false,
    limit: 20,
    lock: false, //点击锁
  },
  async onLoad() {
    const form = wx.getStorageSync('address')
    const user = getUser() || {}
    if (user.vip) {
      user.vip.isVip = checkUserisVip(user)
    }
    this.setData({ ...form, user })
    wx.startPullDownRefresh()
    $event.on('after:boot', this, () => {
      this.getPosition()
    })
    $event.on('after:payCarts', this, () => {
      this.loadData(false)
    })
  },
  onShow() {
    getDomoUser()
    this.getPosition()
  },

  /** 加载数据，购物车数据和推荐数据 */
  async loadData(isLoadMore = false) {
    if (!isLoadMore || !this.data.listLoadAll) {
      await this.getList(isLoadMore)
    } else {
      await this.getPushList(isLoadMore)
    }
  },
  /** 请求推荐数据 */
  async getPushList(isLoadMore = false) {
    const {
      data: { limit },
    } = this
    const pushList = await mallApi.getCommodities({
      liked: 'check',
      offset: isLoadMore ? this.data.pushList.length : 0,
      limit,
      order: 'topped_at desc, updated_at desc',
      with: 'brands',
      type: 'member',
    })
    this.setData({
      /** 购物车列表加载完毕后才会加载推荐数据 */
      listLoadAll: true,
      pushList: isLoadMore ? [...this.data.pushList, ...pushList] : pushList,
      isLastpage: pushList.length < limit,
    })
  },
  /** 请求购物车数据 */
  async getList(isLoadMore = false) {
    const {
      data: { limit },
    } = this
    // eslint-disable-next-line prefer-const
    let { total_count, list } = await mallApi.getCartsList({
      limit,
      offset: isLoadMore ? this.data.list.length : 0,
    })
    if (list.length < limit) {
      // 代表购物车列表已经加载完毕，加载推荐数据
      await this.getPushList()
    }
    list = this.handleData(list)
    this.setData({
      list: isLoadMore ? [...this.data.list, ...list] : list,
      totalCount: total_count,
    })
  },
  async onPullDownRefresh() {
    this.setData({ chooseList: [], selectedAll: false, freight: 0, price: 0 })
    await this.loadData()
    wx.stopPullDownRefresh()
  },
  async onReachBottom() {
    if (this.data.isLastpage) return
    wx.showLoading({ title: '加载中...' })
    await this.loadData(true)
    wx.hideLoading()
  },
  /** 处理数据，本地需要知道，删除、库存等组装字段，方便直接使用 */
  handleData(list: any[]) {
    const {
      data: { user },
    } = this
    list.map((tmp) => {
      tmp.commodities.map((i: any) => {
        i.selected = false
        i.userPrice = i.commodity.market_price
        if (user.vip && user.vip.isVip) {
          i.commodity.extra[`${user.vip.level}`] || i.commodity.extra[`${user.vip.level}`] == 0
            ? (i.userPrice = i.commodity.extra[`${user.vip.level}`])
            : ''
        }
        this.checkProductHasInventory(i)
      })
    })
    this.handleAllShopChooseStatus(list)
    return list
  },
  /**
   *
   * @param list 商家订单数据
   */
  handleAllShopChooseStatus(list: any[]) {
    list.map((tmp) => {
      this.handleShopChooseStatus(tmp)
    })
  },
  /**
   *
   * @param shopOrder 单个商家订单数据
   * @returns
   */
  handleShopChooseStatus(shopOrder: { commodities: any[], shopAllCantBuy: boolean, shopChoosed: boolean }) {
    // 标记是否是所有都不可以购买
    let shopAllCantBuy = true
    // 标记当前商家下的可购买商品是否全部都已经选中了
    let shopChoosed = true

    shopOrder.commodities.forEach((vl: any) => {
      if (vl.inventory) {
        shopAllCantBuy = false
      }
      if (!vl.selected) {
        shopChoosed = false
      }
    })
    shopOrder.shopAllCantBuy = shopAllCantBuy
    shopOrder.shopChoosed = shopChoosed
  },

  // 检查商品是否已经下架
  checkProductDelted(product: any) {
    const hasDeleted = !product.commodity || product.commodity.deleted_at || product.deleted_at
    return hasDeleted
  },
  // 检查商品库存是否充足
  checkProductHasInventory(product: any) {
    // 商品被下架了
    const hasDeleted = this.checkProductDelted(product)
    product.deleted = hasDeleted
    if (hasDeleted) {
      product.inventory = false
    } else {
      if (product.commodity_option) {
        let optionsPrice = 0
        let inventory = true
        product.commodity.sku.forEach((item: any) => {
          if (item.name === product.commodity_option) {
            optionsPrice = item.extra
            // 库存数量大于当前加入的数量，库存充足
            inventory = item.inventory > product.quantity
          }
        })
        product.userPrice = product.userPrice + optionsPrice
        product.commodity.market_price = product.commodity.market_price + optionsPrice
        product.inventory = inventory
      } else {
        // 没有规格的默认满库存
        product.inventory = true
      }
    }
    return product
  },
  getPosition() {
    this.setData({
      access: GlobalData.access,
      exchangeRate: GlobalData.currency.settings['recharge-ratio'],
      currencyName: GlobalData.currencyName,
    })
  },
  chooseAddress() {
    const chooseAddress = () => {
      wx.chooseAddress({
        success: (res) => {
          const form = {
            realname: res.userName,
            phone: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            country: res.countyName,
            detail: res.detailInfo,
          }
          wx.setStorageSync('address', form)

          this.setData(form)
        },
      })
    }

    // 获取收货地址授权信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.address'] === false) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.address'] === false) {
                wx.showToast({ title: '请允许使用您的收货地址', icon: 'none' })
              } else {
                chooseAddress()
              }
            },
          })
          return
        }
      },
    })
    chooseAddress()
  },
  chooseOptions(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      options: e.currentTarget.dataset.item,
    })
  },
  async reduce(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { shopposition, index },
      },
    } = e
    const {
      data: { list },
    } = this
    const product = list[shopposition].commodities[index]
    if (product.quantity < 2) {
      product.quantity = 1
      wx.showToast({
        title: '至少选择一件商品',
        icon: 'none',
      })
      return
    } else {
      product.quantity -= 1
    }
    try {
      await mallApi.changeCarts(+product.id, { quantity: product.quantity }),
        this.setData({
          list,
        })
      product.selected && this.getPrice()
    } catch (error) {
      product.quantity += 1
      wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
    }

  },
  async add(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { shopposition, index },
      },
    } = e
    const {
      data: { list },
    } = this
    const product = list[shopposition].commodities[index]
    try {
      await mallApi.changeCarts(+product.id, { quantity: product.quantity + 1 })
      product.quantity += 1
      product.selected && this.getPrice()
      this.checkProductHasInventory(product)
      this.setData({
        list,
      })
    } catch (error) {
      wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
    }

  },
  /** 结算 */
  async openConfirm() {
    const {
      data: { list },
    } = this
    const priceList = [] as any
    // if (!phone) return WechatMiniprogram.showToast({ title: '请选择收货地址', icon: 'none' })
    // for (const i of list) {
    //   if (
    //     i.selected &&
    //     i.commodity.remote_areas &&
    //     i.commodity.remote_areas.includes(province.slice(0, 2))
    //   ) {
    //     return WechatMiniprogram.showModal({
    //       title: '提示',
    //       content: `抱歉，商品'${i.commodity.title}'暂不支持发货到${province}`,
    //       showCancel: false,
    //       confirmText: '知道了',
    //     })
    //   }
    // }
    list.map((i) => {
      i.commodities.forEach((tmp: any) => {
        tmp.selected && priceList.push(tmp)
      })
    })
    if (priceList.length === 0) {
      wx.showToast({ title: '请至少选择一件商品', icon: 'none' })
      return
    }
    this.setData({ priceList })
    wx.navigateTo({ url: '/mall/cartsPay/cartsPay' })
  },
  /** 管理 */
  operation() {
    const {
      data: { operation },
    } = this
    this.setData({
      operation: !operation,
    })
  },
  /** 商家选择 */
  selectShopAll(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { shopposition },
      },
    } = e
    const {
      data: { list },
    } = this
    list[shopposition].commodities.forEach((vl: any, index: number) => {
      this.handleSelectCommondiy(shopposition, index, !list[shopposition].shopChoosed)
    })
    this.handleShopChooseStatus(list[shopposition])
    this.setData({ list })
  },
  /** 选中/撤销商品,单个 */
  select(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { shopposition, index },
      },
    } = e
    const {
      data: { list },
    } = this
    this.handleSelectCommondiy(shopposition, index, !list[shopposition].commodities[index].selected)
    this.handleShopChooseStatus(list[shopposition])
    this.setData({ list })
  },
  handleSelectCommondiy(shopposition: number, index: number, selected: boolean) {
    const {
      data: { list, chooseList, lock, operation },
    } = this
    const product = list[shopposition].commodities[index]
    /** 商品不可选 */
    if (!product.inventory && !operation) return
    if (lock) return
    this.setData({
      lock: true,
    })
    let arr = []
    /** 在已选择列表添加/删除 */
    if (selected && !chooseList.some((i) => i.id == product.id)) {
      chooseList.push(product)
      arr = chooseList
    } else if (!selected && chooseList.some((i) => i.id == product.id)) {
      arr = chooseList.filter((i) => i.id !== product.id)
    }
    this.setData({
      chooseList: arr,
      [`list[${shopposition}].commodities[${index}].selected`]: selected,
      lock: false,
    })
    this.changeSelect()
  },
  /**底部全选/取消全选 */
  selectAll() {
    const {
      data: { selectedAll, list, operation },
    } = this
    const lists: any[] = []
    list.forEach((tmp) => {
      tmp.commodities.map((i: any) => {
        if (i.inventory || operation) {
          i.selected = !selectedAll
        }
        if (i.selected) {
          lists.push(i)
        }
      })
    })
    // 更新商家的选中状态
    this.handleAllShopChooseStatus(list)
    const chooseList = !selectedAll ? lists.concat() : []
    this.setData({
      chooseList,
      list,
      selectedAll: !selectedAll,
    })
    this.getPrice()
    this.changeSelect()
  },
  /** 单个选中状态改变时，取消/勾选全选 */
  changeSelect() {
    const {
      data: { list, chooseList, operation },
    } = this

    let lists: any[] = []
    list.forEach((i) => {
      i.commodities.forEach((tmp: any) => {
        lists.push(tmp)
      })
    })
    // 如果是管理，所有的都可以操作，否则，被删除或者无库存的不可操作
    if (!operation) {
      lists = lists.filter((i: any) => {
        return i.inventory
      })
    }
    const select = !lists.some((i) => !i.selected) && chooseList.length > 0 && lists.length == chooseList.length
    this.setData({
      selectedAll: select,
    })
    this.getPrice()
  },
  /** 计价函数 */
  getPrice() {
    const {
      data: { list },
    } = this
    let price = 0
    let freight = 0

    list.forEach((tmp => {
      tmp.commodities.map((i: any) => {
        if (i.selected) {
          price += i.userPrice * i.quantity
          freight += i.commodity.freight
        }
      })
    }))

    this.setData({ price, freight })
  },
  /** 清除购物车商品 */
  delete() {
    let {
      data: { list },
    } = this
    const arr = [] as any[]
    list.forEach((tmp) => {
      tmp.commodities.forEach((i: any) => {
        i.selected && arr.push(i.id)
      })
    })

    if (arr.length < 1) {
      wx.showToast({
        title: '并未选择任何商品',
        icon: 'none',
      })
      return
    }
    // 移除列表中删除的内容
    list = list.filter((tmp) => {
      const commodities = tmp.commodities.filter((i: any) => {
        return !i.selected
      })
      tmp.commodities = commodities
      return commodities.length > 0
    })

    mallApi
      .deletCarts({ shopping_cart_ids: arr })
      .then(() => {
        wx.showToast({
          title: '删除成功',
          icon: 'none',
        })
        $event.emit('change:payCarts')
        this.setData({ list, chooseList: [], selectedAll: false, price: 0 })
      })
      .catch(() => {
        wx.showToast({
          title: '删除失败',
          icon: 'none',
        })
      })
  },
  toDetail(e: any) {
    const {
      currentTarget: {
        dataset: { commodityid },
      },
    } = e

    wx.navigateTo({
      url: `/mall/detail/detail?commodityId=${commodityid}`,
    })
  },
})
